package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.Sequence;
import com.ruoyi.system.mapper.SequenceMapper;
import com.ruoyi.system.service.ISequenceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SequenceServiceImpl extends ServiceImpl<SequenceMapper, Sequence> implements ISequenceService {

//    @Transactional
//    @Override
//    public Long atomicIncrement(String name) {
//        baseMapper.increment(name);
//        return baseMapper.getCurrentValue(name);
//    }

//    @Transactional(isolation = Isolation.REPEATABLE_READ)
//    public Long atomicIncrement(String name) {
//        int maxRetries = 3;
//        for (int i = 0; i < maxRetries; i++) {
//            Sequence seq = baseMapper.getSequence(name);
//            int rows = baseMapper.optimisticIncrement(name, seq.getVersion());
//
//            if (rows > 0) {
//                return seq.getValue() + 1; // 更新成功，返回新值
//            }
//
//            // 更新失败，说明有并发冲突，重试
//        }
//
//        throw new RuntimeException("获取序列值失败，重试次数耗尽");
//    }
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public Long atomicIncrement(String name) {
        // 1. 查询并加锁
        Sequence seq = baseMapper.selectForUpdate(name); // SQL: SELECT * FROM sequence WHERE name = #{name} FOR UPDATE

        // 2. 更新值（此时其他线程会被阻塞）
        seq.setValue(seq.getValue() + 1);
        seq.setVersion(seq.getVersion() + 1);
        baseMapper.updateById(seq);

        // 3. 返回新值
        return seq.getValue();
    }
}
